const Koa = require('koa')
const consola = require('consola')
const json = require('koa-json')
const session = require('koa-session')
const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser')
const static = require('koa-static')
const path = require('path')
const jwt = require('koa-jwt');
const {
  logger,
  accessLogger
} = require('./middleware/logger');
const {
  Nuxt,
  Builder
} = require('nuxt');

const app = new Koa()
//日志
app.use(accessLogger());
//接口部分
const passport = require('./utils/passport')
const routes = require('./routers')
//session
app.keys = ['vblog_keys']
const sessionConfig = require('./utils/session')
app.use(session(sessionConfig, app));
//mongoDB
const handleDB = require('./dbs/config')
handleDB.connect();
//静态资源文件
app.use(static(path.join(__dirname, 'assets')))
app.use(static(path.join('F:/', 'directory_temp')))
//跨域
app.use(cors({
  credentials: true
}));
//http解析
app.use(bodyParser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(passport.initialize())
app.use(passport.session())
//jwt认证
// app.use(jwt({
//   secret: 'vblog'
// }).unless({
//   path: [
//     /^\/$/, /\/token/, /\/wechat/,
//     {
//       url: /\/papers/,
//       methods: ['GET']
//     }
//   ]
// }));
//全局捕获ctx.body
const resultHandler = require('./middleware/intercept.js');
resultHandler(app);
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = app.env !== 'production'

async function start() {
  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  const {
    host = process.env.HOST || '127.0.0.1',
      port = process.env.PORT || 3000
  } = nuxt.options.server

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  } else {
    await nuxt.ready()
  }

  app.use(routes.routes()).use(routes.allowedMethods())

  app.use((ctx) => {
    ctx.status = 200
    ctx.respond = false // Bypass Koa's built-in response handling
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  consola.ready({
    message: `Server listening on http://${host}:${port}`,
    badge: true
  })
}

start()
